<template>
  <div>
    <splitpanes class="default-theme" horizontal style="height: 70vh">
      <pane min-size="20" max-size="70">
        <span>1</span>
      </pane>
      <!-- <pane>
        <span>2</span>
      </pane> -->
      <pane max-size="70">
        <span>3</span>
      </pane>
    </splitpanes>
  </div>
</template>
  


<script>
import SearchFormDate from "@/components/SearchFormDate";
import {
  listApplydwd,
  getApplydwd,
  delApplydwd,
  addApplydwd,
  updateApplydwd,
  selectdeptUserSampleNum,
  selectdeptSampleNum,
} from "@/api/sample/applydwd";
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  changeUserStatus,
  deptTreeSelect,
} from "@/api/system/user";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";

export default {
  components: {
    SearchFormDate,
    Splitpanes,
    Pane,
  },
  data() {
    return {
      wmsItemTypeList: [],
      // 要展开的行，数值的元素是row的key值
      // expandRowKeys: [],
      tableHeight: "",
      sums: {},
      height: 750,
      curData: {
        type: 1,
        dateRange: {
          beginTime: "",
          endTime: "",
        },
      },
      params: {
        queryType: 1,
        startDate: "",
        endDate: "",
      },
      // columns: Array.from({ length: 10 }, (_, idx) => ({
      //   prop: 'address', id: idx, label: '地址' + idx, width: 200
      // }))
    };
  },

  // computed: {
  //   treeData() {
  //     const newData = [...this.treeData]; // 创建一个新的数组，避免修改原始数据
  //     const totalRow = { column1: "合计", column2: 0, column3: 0 }; // 合计行的数据

  //     // 计算合计值
  //     // this.treeData.forEach(item => {
  //     //     totalRow.column2 += item.column2;
  //     //     totalRow.column3 += item.column3;
  //     // });
  //     // 将合计行插入到正确的位置
  //     newData.splice(4, 0, totalRow); // 假设将合计行插入到第二行的位置

  //     return newData;
  //   }
  // },
  mounted() {
    // console.log(500 + (500 * 500) + (500 * 500 * 10))
    // const data = Array.from({ length: 500 }, (_, idx) => ({
    //     id: idx + '_' + 1,
    //     date: '2016-05-03',
    //     name: 1,
    //     ab: '欢迎使用u-table',
    //     address: idx,
    //     children: Array.from({ length: 2 }, (_, idx2) => ({
    //         id: idx + '_' + idx2 + '_' + 1,
    //         date: '2016-05-03',
    //         name: 1,
    //         ab: '欢迎使用u-table',
    //         address: idx + '_' + idx2,
    //         children: Array.from({ length: 1 }, (_, idx3) => ({
    //             id: idx + '_' + idx2 + '_' + idx3 + '_' + 1,
    //             date: '2016-05-03',
    //             name: 1,
    //             ab: '欢迎使用u-table',
    //             address: idx + '_' + idx2 + '_' + idx3
    //         }))
    //     }))
    // }));
    // var data = []
    // deptTreeSelect().then(response => {
    //     // this.treeData = response.data;
    //     data = response.data;
    //     console.log(JSON.stringify(data));
    //     this.treeData = data // 知道为啥treeData不在 data()方法里面定义吗？嘻嘻
    //     // 设置表格数据
    //     this.$refs.plTreeTable.reloadData(data)
    //     // 获取表格实例，里面可以得到列，表格数据等等
    //     console.log(this.$refs.plTreeTable.tableExample())
    // });
    // console.log(JSON.stringify(data));
    // this.getList()
    // this.getselectdeptSampleNum()
  },
  methods: {
    selectChangeEvent(rows) {
      console.log(rows);
    },
    getTreeExpansionEvent() {
      let treeExpandRecords = this.$refs.plxTree.getTreeExpandRecords();
      console.log(treeExpandRecords);
    },

    child(objArgu, weekTime) {
      this.objArgu = objArgu;
      this.params.queryType = objArgu.cType;
      this.params.startDate = objArgu.beginTime;
      this.params.endDate = objArgu.endTime;
      this.weekTime = weekTime;
      console.log(JSON.stringify(this.params));
      // if (this.params.queryType == 1) {
      //     // console.log(1);
      //     const obj = { sampleDayStart: this.params.startDate, sampleDayEnd: this.params.endDate }
      //     this.getselectdeptSampleNum(obj)
      //     this.getList(obj)

      // }
      // if (this.params.queryType == 3) {
      // console.log(1);
      const obj = {
        dateYearStart: this.params.startDate.slice(0, 4),
        dateYearEnd: this.params.endDate.slice(0, 4),
        dateMonthStart: this.params.startDate.slice(5, 7),
        dateMonthEnd: this.params.endDate.slice(5, 7),
      };
      console.log(JSON.stringify(obj));
      // return
      this.getselectdeptSampleNum(obj);
      this.getList(obj);

      // }
      // if (this.params.queryType == 4) {
      //     // console.log(1);
      //     const obj = { dateYearStart: this.params.startDate.slice(0, 4), dateYearEnd: this.params.endDate.slice(0, 4) }
      //     console.log(JSON.stringify(obj));
      //     // return
      //     this.getselectdeptSampleNum(obj)
      //     this.getList(obj)

      // }
    },
    getList(queryParams) {
      // this.sums = this.getselectdeptSampleNum(queryParams)
      selectdeptUserSampleNum(queryParams).then((response) => {
        // this.applydwdList = response;
        const tree = this.convertToTree(response);
        console.log(JSON.stringify(tree));
        const data = [];
        for (let key in tree) {
          console.log(key); // 输出对象的键（"商品部"和"采购部"）
          console.log(JSON.stringify(tree[key])); // 输出对象的值（对应的子对象）
          data.push(tree[key]);
        }
        console.log(JSON.stringify(data));

        // const totalRow = { userName: "汇总", sampleNum: this.sums.sampleNum, returnedNum: this.sums.returnedNum, returnedRatioStr: this.sums.returnedRatio, returnNum: this.sums.returnNum, noReturnNum: this.sums.noReturnNum, returnRatioStr: this.sums.returnRatio }; // 合计行的数据
        // // const totalRow = { userName: "汇总", sampleNum: sums.sampleNum, returnedNum: sums.returnedNum, returnedRatioStr: sums.returnedRatio, returnNum: sums.returnNum, noReturnNum: sums.noReturnNum, returnRatioStr: sums.returnRatio }; // 合计行的数据
        // data.splice(0, 0, totalRow); // 假设将合计行插入到第二行的位置

        this.treeData = data; // 知道为啥treeData不在 data()方法里面定义吗？嘻嘻
        // 设置表格数据
        this.wmsItemTypeList = data;
        this.$forceUpdate();

        // this.$nextTick(() => {
        // this.$refs.plTreeTable.reloadData(data)
        // });
      });
    },
    //汇总
    getselectdeptSampleNum(queryParams) {
      selectdeptSampleNum(queryParams).then((data) => {
        const result = data.reduce(
          (accumulator, currentValue) => {
            accumulator.sampleNum += currentValue.sampleNum;
            accumulator.returnNum += currentValue.returnNum;
            accumulator.noReturnNum += currentValue.noReturnNum;
            accumulator.returnedNum += currentValue.returnedNum;
            accumulator.returnedRatio =
              Number(
                (accumulator.returnedNum / accumulator.sampleNum) * 100
              ).toFixed(2) + "%";
            accumulator.returnRatio =
              (
                (accumulator.returnNum /
                  (Number(accumulator.returnNum) +
                    Number(accumulator.noReturnNum))) *
                100
              ).toFixed(2) + "%";

            return accumulator;
          },
          {
            sampleNum: 0,
            returnNum: 0,
            noReturnNum: 0,
            returnedNum: 0,
            returnedRatio: "",
            returnRatio: "",
          }
        );
        this.sums = result;
        this.$forceUpdate();

        console.log(JSON.stringify(result));
        // return result
      });
    },
    //树
    convertToTree(data) {
      const tree = {};
      data.forEach((item) => {
        const deptName = item.deptName;
        if (!tree[deptName]) {
          // tree[deptName] = {
          tree[deptName] = {
            children: [],
            // count: 0,
            sampleNum: 0,
            returnNum: 0,
            noReturnNum: 0,
            returnedNum: 0,
            sendRatio: 0,
            returnRatio: 0,
            returnedRatio: 0,
            returnRatioStr: "",
            returnedRatioStr: "",
            userName: item.deptName,
            id: 0,
          };
        }
        // tree[deptName].children.push(item);
        tree[deptName].children.push(item);
        tree[deptName].id++;
        tree[deptName].sampleNum += item.sampleNum;
        tree[deptName].returnNum += item.returnNum;
        tree[deptName].noReturnNum += item.noReturnNum;
        tree[deptName].returnedNum += item.returnedNum;
        tree[deptName].sendRatio += item.sendRatio;
        tree[deptName].returnRatio += item.returnRatio;
        tree[deptName].returnedRatio += item.returnedRatio;
      });

      // Calculate average values
      Object.values(tree).forEach((node) => {
        // node.sendRatio /= node.count;
        // node.returnRatio /= node.count;
        // node.returnedRatio /= node.count;
        node.returnRatioStr =
          (
            (node.returnNum /
              (Number(node.returnNum) + Number(node.noReturnNum))) *
            100
          ).toFixed(2) + "%";
        node.returnedRatioStr =
          ((node.returnedNum / node.sampleNum) * 100).toFixed(2) + "%";
      });
      // const totalRow = {
      //     "汇总": { id: 0, userName: "汇总", sampleNum: this.sums.sampleNum, returnedNum: this.sums.returnedNum, returnedRatio: this.sums.returnedRatio, returnNum: this.sums.returnNum, noReturnNum: this.sums.noReturnNum, returnRatio: this.sums.returnRatio, children: [] }
      // }; // 合计行的数据}
      // const totalRow = { userName: "汇总", sampleNum: sums.sampleNum, returnedNum: sums.returnedNum, returnedRatioStr: sums.returnedRatio, returnNum: sums.returnNum, noReturnNum: sums.noReturnNum, returnRatioStr: sums.returnRatio }; // 合计行的数据
      // tree.push(totalRow); // 假设将合计行插入到第二行的位置
      // tree = { ...tree, ...totalRow };

      return tree;
    },
    //合计行
    addTotal({ columns, data }) {
      // const { columns, data } = param;
      const sums = [];
      columns.forEach((column, columnIndex) => {
        if (columnIndex === 0) {
          sums[columnIndex] = "总计";
          return;
        }
        // if (columnIndex === 2) {
        //   sums[columnIndex] = 'N/A';
        //   return;
        // }
        // if (columnIndex  === 3) {
        //   sums[columnIndex ] = 'N/A';
        //   return;
        // }
        const values = data.map((item) => Number(item[column.property]));

        if (!values.every((value) => isNaN(value))) {
          sums[columnIndex] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[columnIndex] += "";
        } else {
          sums[columnIndex] = "N/A";
        }

        if (columnIndex === 3) {
          var point = sums[2] / sums[1];
          var str = Number(point * 100).toFixed(2);
          str += "%";
          sums[columnIndex] = str;
        }
        if (columnIndex === 6) {
          var sum = Number(sums[4]) + Number(sums[5]);
          console.log(sum);
          var point = sums[4] / sum;
          var str = Number(point * 100).toFixed(2);
          str += "%";
          sums[columnIndex] = str;
        }
      });
      this.sums = sums;

      console.log(JSON.stringify(sums));
      return sums;
    },
    // 获取已经展开的节点
    // getTreeExpansionEvent() {
    //     console.log(this.$refs.plTreeTable.getTreeExpandRecords())
    // },
    // 收起展开时触发
    toggleTreeExpand(row, treeExpanded, event) {
      console.log(row, treeExpanded, event);
      console.log(JSON.stringify(row));
      console.log(JSON.stringify(treeExpanded));
      console.log(JSON.stringify(event));
      // treeExpanded.forEach(item => {
      //   this.expandRowKeys.push(row);
      // });
    },
  },
};
</script>
 
<style lang="scss">
.el-select .el-input {
  width: 100% !important;
}

.header {
  text-align: center;
  line-height: 23px;
  font-size: 13px;
  border: 1px solid #ebeef5;
  padding: 10px 0;
  // font-weight: 510;
  // font-style: italic;
  // font-family: Haettenschweiler // , Helvetica, sans-serif Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif
}
</style>